package top.akame.webs.utils;

import java.time.Instant;

/**
 * @AUObjectHOR soft
 * @DAObjectE 2018/10/30 14:55
 * @DESCRIBE 统一的Json返回类
 */
public class RestResponse {
    private Object payload;

    private boolean success;
    private String message;
    private Integer status = 0;
    private long timestamp;

    public RestResponse() {
        this.timestamp = nowUnix();
    }

    public RestResponse(boolean success) {
        this.timestamp = nowUnix();
        this.success = success;
    }

    public RestResponse(boolean success, Object payload) {
        this.timestamp = nowUnix();
        this.success = success;
        this.payload = payload;
    }

    public RestResponse success(boolean success) {
        this.success = success;
        return this;
    }

    public RestResponse payload(Object payload) {
        this.payload = payload;
        return this;
    }

    public RestResponse status(Integer status) {
        this.status = status;
        return this;
    }

    public RestResponse message(String msg) {
        this.message = msg;
        return this;
    }

    public static RestResponse ok() {
        return new RestResponse().success(true).status(200);
    }

    public static RestResponse tip(String message) {
        return new RestResponse().success(true).message(message).status(200);
    }

    public static RestResponse tip(String message, Integer status) {
        return new RestResponse().success(true).message(message).status(status);
    }

    public static RestResponse ok(Object payload) {
        return new RestResponse().success(true).payload(payload).status(200);
    }

    public static RestResponse ok(Object payload, Integer code) {
        return new RestResponse().success(true).payload(payload).status(code);
    }

    public static RestResponse fail() {
        return new RestResponse().success(false).status(404);
    }

    public static RestResponse fail(String message) {
        return new RestResponse().success(false).message(message).status(404);
    }

    public static RestResponse fail(Object payload) {
        return new RestResponse().success(false).message("").status(404).payload(payload);
    }

    public static RestResponse fail(Integer code, String message) {
        return new RestResponse().success(false).message(message).status(code);
    }

    public static RestResponse fail(Integer code, Object payload) {
        return new RestResponse().success(false).payload(payload).status(code);
    }

    private long nowUnix() {
        return Instant.now().getEpochSecond();
    }


    public Object getPayload() {
        return payload;
    }

    public boolean isSuccess() {
        return success;
    }

    public String getMessage() {
        return message;
    }

    public Integer getStatus() {
        return status;
    }

    public long getTimestamp() {
        return timestamp;
    }
}
